package com.zq.it.cms.support;

import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.SmartView;
import org.springframework.web.servlet.View;

import com.zq.it.cms.common.Constants;
import com.zq.it.cms.common.Context;
import com.zq.it.cms.common.Servlets;
import com.zq.it.cms.domain.User;

public class BackInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		User user = null;
		if (subject.isAuthenticated()) {
			Object principal = subject.getPrincipal();
			if(principal instanceof User){
				user = (User) principal;
			}else{
				subject.logout();
			}
		}
		if(user != null){
			Context.setCurrentUser(user);
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		if (modelAndView == null || !modelAndView.hasView()) {
			return;
		}
		boolean isRedirect = false;
		if (modelAndView.isReference()) {
			String viewName = modelAndView.getViewName();
			isRedirect = StringUtils.startsWith(viewName, "redirect:");
		} else {
			View view = modelAndView.getView();
			if (view instanceof SmartView) {
				isRedirect = ((SmartView) view).isRedirectView();
			}
		}
		ModelMap modelMap = modelAndView.getModelMap();
		// 重定向不需要加ctx参数
		if (!isRedirect) {
			String ctx = request.getContextPath();
			if ("/".equals(ctx)) {
				// 在Controller里forward之后，ctx会变成/
				ctx = "";
			}
			modelMap.addAttribute(Constants.CTX, ctx);
		}
		Map<String, String[]> searchMap = Servlets.getParamValuesMap(request, Constants.SEARCH_PREFIX, true);
		Map<String, String[]> pageMap = Servlets.getParamValuesMap(request, Constants.PAGE_PREFIX, true);
		searchMap.putAll(pageMap);
		for (Entry<String, String[]> entry : searchMap.entrySet()) {
			String[] value = entry.getValue();
			// 避免jsp的el表达式出现 0 eq ''的情况
			if (value != null && value.length > 0 && (!"".equals(value[0]) || value.length > 1)) {
				// modelMap.addAllAttributes(searchMap);
				modelMap.addAttribute(entry.getKey(), value);
			}
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		Context.resetCurrentUser();
	}

}
